package com.zj.osm.utils;

import android.os.Environment;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ZipUtils;
import com.thoughtworks.xstream.core.util.Base64Encoder;
import com.zj.osm.App;
import com.zj.osm.entity.db.PointDao;
import com.zj.osm.entity.greendao.Equipment;
import com.zj.osm.entity.greendao.Line;
import com.zj.osm.entity.greendao.Photos;
import com.zj.osm.entity.greendao.Point;
import com.zj.osm.entity.greendao.Project;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;
/**
 * Created by Jiang on 2019/2/28
 */
public class ParseXmls {
    private static final ParseXmls ourInstance = new ParseXmls();

    public static ParseXmls getInstance() {
        return ourInstance;
    }

    private ParseXmls() {
    }

    private Long cid;

    /**
     * 解析在线项目数据
     * @param xmlData 从服务器获取的数据
     * @return
     */
    public Boolean parseXMLWithPulls(String xmlData, Project items, Long cid) {
        this.cid = cid;
        String code = null;
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            //设置输入的内容
            xmlPullParser.setInput(new StringReader(xmlData));
            //获取当前解析事件，返回的是数字
            int eventType = xmlPullParser.getEventType();
            //保存内容

            String data = "";
            while (eventType != (XmlPullParser.END_DOCUMENT)) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    //开始解析XML
                    case XmlPullParser.START_TAG: {
                        //nextText()用于获取结点内的具体内容
                        if ("code".equals(nodeName)) {
                            code = xmlPullParser.nextText();
                            /*if (code.equals("success"))
                                return true;*/
                        }
                        if ("data".equals(nodeName)) {
                            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                                    + "/bhne/" + items.getProjectId() + "/" + items.getProjectId() + ".zip");

                            OutputStream output = new FileOutputStream(file);

                            BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);

                            data = xmlPullParser.nextText();
                            Base64Encoder encoder = new Base64Encoder();
                            byte[] zhu = encoder.decode(data);
                            bufferedOutput.write(zhu);
                            File files = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                                    + "/bhne/" + items.getProjectId());
                            ZipUtils.unzipFile(file, files);
                            List<File> stringList;
                            stringList = FileUtils.listFilesInDir(files);
                            for (int i = 0; i < stringList.size(); i++) {
                                if (stringList.get(i).getName().contains(".xml")) {
                                    String result = getXmlString(stringList.get(i).getPath());
                                    try {
                                        parseXMLPull(result, Environment.getExternalStorageDirectory().getAbsolutePath()
                                                + "/bhne/" + items.getProjectId() + "/");
                                    } catch (DocumentException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            output.close();
                            bufferedOutput.close();
                        }
                    }
                    break;
                    //结束解析
                    case XmlPullParser.END_TAG: {
                    }
                    break;
                    default:
                        break;
                }
                //下一个
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return code != null;
    }


    /**
     * 将xml文件转换成字符串
     *
     * @param path 文件路径
     * @return 转换完成的字符串
     */
    public String getXmlString(String path) {
        String xmlString;
        byte[] strBuffer = null;
        int flen = 0;
        File xmlfile = new File(path);
        try {
            InputStream in = new FileInputStream(xmlfile);
            flen = (int) xmlfile.length();
            strBuffer = new byte[flen];
            in.read(strBuffer, 0, flen);
            in.close();
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        xmlString = new String(strBuffer); //构建String时，可用byte[]类型，
        return xmlString;
    }


    /**
     * 通过解析出来的xml数据更新到服务器所有的点。
     *
     * @param str xml数据
     * @throws DocumentException 抛出异常
     */
    public void parseXMLPull(String str, String path) throws DocumentException {
        List<Point> pointsList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(cid)).build().list();
        for (int i = 0; i < pointsList.size(); i++) {
            App.getInstances().getDaoSession().getPointDao().delete(pointsList.get(i));
        }
        Document doc = DocumentHelper.parseText(str);
        Element projects = doc.getRootElement();
        Iterator Elements = projects.elementIterator();
        while (Elements.hasNext()) {
            Element pl = (Element) Elements.next();
            switch (pl.getName()) {
                case "ProjectId":
                    break;
                case "Point": {
                    List attrList = pl.attributes();

                    Point points = new Point();
                    points.setProjectId(cid);
                    points.setId(null);
                    for (int i = 0; i < attrList.size(); i++) {
                        //Point属性的取得
                        Attribute item = (Attribute) attrList.get(i);
                        if (item.getName().equals("Dangjv")) {
                            points.setDangju(Double.parseDouble(item.getValue()));
                        }
                        if (item.getName().equals("Weidu")) {
                            points.setLatitude(Double.parseDouble(item.getValue()));
                        }
                        if (item.getName().equals("Jindu")) {
                            points.setLongitude(Double.parseDouble(item.getValue()));
                        }
                        if (item.getName().equals("Glsb")) {
                            points.setGlsb(item.getValue());
                        }
                        if (item.getName().equals("Sbzt")) {
                            points.setState(item.getValue());
                        }
                        if (item.getName().equals("Sbbh")) {
                            points.setMark(item.getValue());
                        }
                        if (item.getName().equals("High")) {
                            points.setHigh(item.getValue());
                        }
                        if (item.getName().equals("Sblb")) {
                            points.setEquipType_name(item.getValue());
                        }
                        if (item.getName().equals("Sblx")) {
                            points.setSblx(item.getValue());
                        }
                        if (item.getName().equals("Ms")) {
                            points.setNote(item.getValue());
                        }
                        if (item.getName().equals("UID")) {
                            points.setUid(item.getValue());
                        }

                    }


                    App.getInstances().getDaoSession().getPointDao().insert(points);
                    //pointlist.add(pointmap);
                    Iterator Elementspl = pl.elementIterator();
                    while (Elementspl.hasNext()) {
                        Element point = (Element) Elementspl.next();
                        //Point子节点属性的取得
                        switch (point.getName()) {
                            case "ColumnModel": {
                                Equipment equipment = new Equipment();
                                equipment.setPointId(points.getId());
                                equipment.setQubie(2);
                                equipment.setId(null);
                                List ColumnModel = point.attributes();
                                for (int i = 0; i < ColumnModel.size(); i++) {
                                    Attribute item = (Attribute) ColumnModel.get(i);
                                    if (item.getName().equals("ModuleFL_Name")) {
                                        equipment.setName(item.getValue());
                                    }
                                    if (item.getName().equals("ModuleFL_ID")) {
                                        equipment.setLever_id(item.getValue());
                                    }
                                    if (item.getName().equals("ModuleZL_Name")) {
                                        equipment.setTwoName(item.getValue());
                                    }
                                    if (item.getName().equals("ModuleZL_ID")) {
                                        equipment.setHead_id(item.getValue());
                                    }
                                    if (item.getName().equals("ModuleXH_Name")) {
                                        equipment.setThreeName(item.getValue());
                                    }
                                    if (item.getName().equals("ModuleXH_ID")) {
                                        equipment.setThreeId(item.getValue());
                                    }
                                    if (item.getName().equals("Module_Name")) {
                                        equipment.setFourName(item.getValue());
                                    }
                                    if (item.getName().equals("Module_ID")) {
                                        equipment.setFourId(item.getValue());
                                    }
                                    if (item.getName().equals("Amount")) {
                                        equipment.setAmount(Integer.parseInt(item.getValue()));
                                    }
                                }
                                App.getInstances().getDaoSession().getEquipmentDao().insert(equipment);
                                break;
                            }
                            case "PointModel": {
                                Equipment equipment = new Equipment();
                                equipment.setPointId(points.getId());
                                equipment.setQubie(0);
                                equipment.setId(null);
                                List ColumnModel = point.attributes();
                                for (int i = 0; i < ColumnModel.size(); i++) {
                                    Attribute item = (Attribute) ColumnModel.get(i);
                                    if (item.getName().equals("ModuleFL_Name")) {
                                        equipment.setName(item.getValue());
                                    }
                                    if (item.getName().equals("ModuleFL_ID")) {
                                        equipment.setLever_id(item.getValue());
                                    }
                                    if (item.getName().equals("ModuleZL_Name")) {
                                        equipment.setTwoName(item.getValue());
                                    }
                                    if (item.getName().equals("ModuleZL_ID")) {
                                        equipment.setHead_id(item.getValue());
                                    }
                                    if (item.getName().equals("ModuleXH_Name")) {
                                        equipment.setThreeName(item.getValue());
                                    }
                                    if (item.getName().equals("ModuleXH_ID")) {
                                        equipment.setThreeId(item.getValue());
                                    }
                                    if (item.getName().equals("Module_Name")) {
                                        equipment.setFourName(item.getValue());
                                    }
                                    if (item.getName().equals("Module_ID")) {
                                        equipment.setFourId(item.getValue());
                                    }
                                    if (item.getName().equals("Amount")) {
                                        equipment.setAmount(Integer.parseInt(item.getValue()));
                                    }
                                }
                                App.getInstances().getDaoSession().getEquipmentDao().insert(equipment);
                                break;
                            }
                            case "Multimedia": {
                                Photos photos = new Photos();
                                photos.setPoints_id(points.getId());
                                photos.setId(null);
                                List ColumnModel = point.attributes();
                                for (int i = 0; i < ColumnModel.size(); i++) {
                                    Attribute item = (Attribute) ColumnModel.get(i);
                                    if (item.getName().equals("Multimedia_Path")) {
                                        photos.setName(item.getValue());
                                        photos.setPath(path + item.getValue());
                                    }
                                }
                                App.getInstances().getDaoSession().getPhotosDao().insert(photos);
                                break;
                            }
                        }
                    }
                    break;
                }
                case "Line": {
                    Line line = new Line();
                    line.setItem_id(cid);
                    List lineList = pl.attributes();

                    for (int i = 0; i < lineList.size(); i++) {
                        //line属性的取得
                        Attribute item = (Attribute) lineList.get(i);
                        if (item.getName().equals("Start_equip")) {
                            line.setStart_id(item.getValue());
                        }
                        if (item.getName().equals("End_equip")) {
                            line.setEnd_id(item.getValue());
                        }
                        if (item.getName().equals("Line_code")) {
                            line.setName(item.getValue());
                        }
                        if (item.getName().equals("LineLen")) {
                            line.setLength(item.getValue());
                        }
                        if (item.getName().equals("LineType")) {
                            line.setType(item.getValue());
                        }
                        if (item.getName().equals("LineStatue")) {
                            line.setState(item.getValue());
                        }
                        if (item.getName().equals("LineBackNum")) {
                            line.setBackNum(item.getValue());
                        }
                        if (item.getName().equals("LineNum")) {
                            line.setNum(item.getValue());
                        }
                        if (item.getName().equals("LineTypeID")) {
                            line.setTypeId(item.getValue());
                        }
                        if (item.getName().equals("LineLonB")) {
                            line.setLonB(item.getValue());
                        }
                        if (item.getName().equals("LineLatB")) {
                            line.setLatB(item.getValue());
                        }
                        if (item.getName().equals("LineLonA")) {
                            line.setLonA(item.getValue());
                        }
                        if (item.getName().equals("LineLatA")) {
                            line.setLatA(item.getValue());
                        }
                        if (item.getName().equals("LineName")) {
                            line.setName(item.getValue());
                        }
                    }
                    App.getInstances().getDaoSession().getLineDao().insert(line);
                    Iterator Elementlinez = pl.elementIterator();
                    while (Elementlinez.hasNext()) {
                        Equipment equipment = new Equipment();
                        equipment.setQubie(1);
                        equipment.setId(null);
                        Element lines = (Element) Elementlinez.next();
                        //Line子节点属性的取得
                        if (lines.getName().equals("LineModel")) {
                            List lineModel = lines.attributes();
                            for (int i = 0; i < lineModel.size(); i++) {
                                Attribute item = (Attribute) lineModel.get(i);
                                if (item.getName().equals("ModuleFL_Name")) {
                                    equipment.setName(item.getValue());
                                }
                                if (item.getName().equals("ModuleFL_ID")) {
                                    equipment.setLever_id(item.getValue());
                                }
                                if (item.getName().equals("ModuleZL_Name")) {
                                    equipment.setTwoName(item.getValue());
                                }
                                if (item.getName().equals("ModuleZL_ID")) {
                                    equipment.setHead_id(item.getValue());
                                }
                                if (item.getName().equals("ModuleXH_Name")) {
                                    equipment.setThreeId(item.getValue());
                                }
                                if (item.getName().equals("ModuleXH_ID")) {
                                    equipment.setThreeId(item.getValue());
                                }
                                if (item.getName().equals("Module_Name")) {
                                    equipment.setFourName(item.getValue());
                                }
                                if (item.getName().equals("Module_ID")) {
                                    equipment.setFourId(item.getValue());
                                }
                                if (item.getName().equals("Amount")) {
                                    equipment.setAmount(Integer.parseInt(item.getValue()));
                                }
                            }
                            App.getInstances().getDaoSession().getEquipmentDao().insert(equipment);
                        }
                    }
                    break;
                }
                case "TopographicPoint": {
                    List lineList = pl.attributes();
                    Point points = new Point();
                    points.setProjectId(cid);
                    points.setId(null);
                    for (int i = 0; i < lineList.size(); i++) {
                        //line属性的取得
                        Attribute item = (Attribute) lineList.get(i);
                        if (item.getName().equals("name")) {
                            points.setName(item.getValue());
                        }
                        if (item.getName().equals("center_lat")) {
                            points.setLatitude(Double.parseDouble(item.getValue()));
                        }
                        if (item.getName().equals("center_lng")) {
                            points.setLongitude(Double.parseDouble(item.getValue()));
                        }
                        if (item.getName().equals("address")) {
                            points.setAddress(item.getValue());
                        }
                        if (item.getName().equals("t_length")) {
                            points.setLength(item.getValue());
                        }
                        if (item.getName().equals("t_width")) {
                            points.setWidth(item.getValue());
                        }
                        if (item.getName().equals("t_hight")) {
                            points.setHigh(item.getValue());
                        }
                        if (item.getName().equals("t_type")) {
                            points.setSblx(item.getValue());
                        }
                        if (item.getName().equals("equipId")) {
                            points.setEquipType_id(Integer.parseInt(item.getValue()));
                        }
                        if (item.getName().equals("remark")) {
                            points.setNote(item.getValue());
                        }
                        if (item.getName().equals("uid")) {
                            points.setUid(item.getValue());
                        }
                    }
                    App.getInstances().getDaoSession().getPointDao().insert(points);
                    break;
                }
            }
        }
    }

}
